package com.bidv.wcm;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bidv.util.DateUtil;
import com.bidv.util.StringUtil;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;
import com.ibm.workplace.wcm.api.Content;
import com.ibm.workplace.wcm.api.DocumentId;
import com.ibm.workplace.wcm.api.DocumentIdIterator;
import com.ibm.workplace.wcm.api.DocumentLibrary;
import com.ibm.workplace.wcm.api.DocumentTypes;
import com.ibm.workplace.wcm.api.ImageComponent;
import com.ibm.workplace.wcm.api.RichTextComponent;
import com.ibm.workplace.wcm.api.TextComponent;
import com.ibm.workplace.wcm.api.WCM_API;
import com.ibm.workplace.wcm.api.Workspace;

/**
 * Servlet implementation class Homepage
 */
@WebServlet("/Homepage")
public class Homepage extends HttpServlet {

	private static final String SUB_TITLE = "SubTitle";
	private static final String IMAGE_SUBTITLE = "ImageSubtitle";
	private static final String DESCRIPTION_FIRST_TITLE = "description";
	private static final String IMAGE_FIRST_TITLE = "image";
	private static final String TOTAL = "total";
	private static final String HREF = "href";
	private static final String MODIFIED_DATE = "modifiedDate";
	private static final String LABEL_DOC = "label";
	private static final String DETAIL_JSP_WCM_WPS_WCM_CONNECT = "detail.jsp?wcm=/wps/wcm/connect/";
	private static final String TEMPLATE = "TempNews";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Homepage() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setContentType("application/json");
			// bien json
			PrintWriter out = response.getWriter();
			JSONArray jsonArray = new JSONArray();
			JSONObject json = null;

			int startPage = Integer.parseInt(request.getParameter("StartPage"));
			int pageSize = Integer.parseInt(request.getParameter("PageSize"));
			String site = request.getParameter("Site");
			String library = request.getParameter("Library");
			String dir = request.getParameter("Dir");
			int k = 1;

			DocumentId siblingId = null;
			DocumentId authoringTmpl = null;
			DocumentId siteArea = null;
			DocumentIdIterator authoringIterator = null;
			DocumentIdIterator siteAreaIterator = null;
			DocumentId<Content> contentid = null;
			Content content = null;

			Workspace myworkspace = WCM_API.getRepository()
					.getSystemWorkspace();
			myworkspace.login();

			DocumentLibrary MyLibrary = myworkspace.getDocumentLibrary(library);
			myworkspace.setCurrentDocumentLibrary(MyLibrary);

			// find Authoring template
			authoringIterator = myworkspace.findByName(
					DocumentTypes.AuthoringTemplate, TEMPLATE);
			// get authoring template of lib
			authoringTmpl = authoringIterator.next();
			// find Sitearea
			siteAreaIterator = myworkspace.findByName(DocumentTypes.SiteArea,
					site);
			// get siteArea
			siteArea = siteAreaIterator.next();

			/*
			 * contentSearch(DocumentId templateId, DocumentId[] siteAreaIds,
			 * DocumentId[] categoryIds, java.lang.String[] keywords, boolean
			 * matchAllCategories, boolean includeAncestorCategories, boolean
			 * includeDescendentCategories, boolean includeAncestorSiteAreas,
			 * boolean includeDescendentSiteAreas, java.lang.String sortKey1,
			 * java.lang.String sortKey2, java.lang.String sortKey3, boolean
			 * sortAscending, int workflowStatusFilter)
			 */

			DocumentIdIterator<Content> docContent = myworkspace.contentSearch(
					authoringTmpl, new DocumentId[] { siteArea }, null,
					null, false, false, false, false,
					false, Workspace.SORT_KEY_PUBLISH_DATE, null, null, false,
					Workspace.WORKFLOWSTATUS_PUBLISHED);

			// scan document
			while (docContent.hasNext() && k > pageSize * (startPage - 1)
					&& k <= pageSize * startPage) {
				contentid = docContent.next();

				String url = "";
				String label = "";
				String image = "";
				String description = "";
				/* khoi tao jsonobject */
				json = new JSONObject();

				content = myworkspace.getById(contentid);

				label = content.getTitle();

				url = DETAIL_JSP_WCM_WPS_WCM_CONNECT + library + "/" + library
						+ "/" + site + "/" + content.getName();

				// neu la ban ghi dau tien thi tra them image va description
				if (k == pageSize * (startPage - 1) + 1) {
					ImageComponent imageComponent = (ImageComponent) content
							.getComponent(IMAGE_SUBTITLE);
					TextComponent rtDescription = (TextComponent) content
							.getComponent(SUB_TITLE);
					description = rtDescription.getText();
					if (imageComponent.getImageFileName() != null
							&& !"".equals(imageComponent.getImageFileName())) {
						image = StringUtil.replaceMyConnect(imageComponent
								.getResourceURL());
					}
				}

				json.put(LABEL_DOC, label);
				json.put(MODIFIED_DATE, DateUtil.getDate(
						content.getModifiedDate(), DateUtil.SHORT_DATE_PATTERN));
				json.put(HREF, url);
				json.put(IMAGE_FIRST_TITLE, image);
				json.put(DESCRIPTION_FIRST_TITLE, description);
				// add vao mang jsonarray
				jsonArray.add(json);

				k++;
			}

			out.print(jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
